<template>
  <div class="w-[480px]">
    <div class="p-4">
      <BaseTitle title="表头设置" />
      <a-table class="settingTable" :columns="settingColumns" row-key="id" :data-source="tableData" size="small" :pagination="false" :scroll="{ y: 400 }">
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'isHide'">
            <a-switch :checked="!record.isHide" size="small" />
          </template>
          <template v-if="column.dataIndex === 'title'">
            <span>{{ record.title || record.dataIndex }}</span>
          </template>
          <template v-if="column.dataIndex === 'edit'">
            <a-button type="link" size="small">
              <BaseIcon name="FormOutlined" />
            </a-button>
          </template>
          <template v-if="column.dataIndex === 'sort'">
            <div class="w-full cursor-move"><BaseIcon name="MenuOutlined" /></div>
          </template>
        </template>
      </a-table>
    </div>
    <div class="flex justify-between mt-2 border-t p-4">
      <a-button type="primary" ghost>重置预设</a-button>
      <div>
        <a-button>取消</a-button>
        <a-button class="ml-2" type="primary">保存</a-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { nextTick, watch } from 'vue'
import Sortable from 'sortablejs'

const props = defineProps({
  columnData: {
    type: Array,
    default: () => []
  }
})
const tableData = ref([])
const settingColumns = [
  { title: '序号', dataIndex: 'indexNumber', width: 60 },
  { title: '表头名称', dataIndex: 'title' },
  { title: '是否显示', dataIndex: 'isHide' },
  { title: '编辑', dataIndex: 'edit' },
  { title: '排序', dataIndex: 'sort' }
]
const initSortTable = () => {
  const tableBody = document.querySelector('.settingTable .ant-table-tbody')
  Sortable.create(tableBody, {
    animation: 150,
    dragClass: 'dragClass', // 拖拽对象移动样式
    ghostClass: 'sortable-ghost', //拖拽样式
    // 结束拖动事件
    onEnd: (evt) => {
      // const { oldIndex, newIndex } = evt
      // const movedItem = tableData.value.splice(oldIndex, 1)[0]
      // tableData.value.splice(newIndex, 0, movedItem)
      // tableData.value = tableData.value.map((item, index) => {
      //   item.indexNumber = index + 1
      //   return item
      // })
      evt.item.classList.add('drag-end')
    }
  })
}
watch(
  () => props.columnData,
  (val) => {
    tableData.value = val
    val.length && nextTick(() => initSortTable())
  },
  {
    immediate: true
  }
)
</script>
<style lang="less">
.drag-end {
  background-color: #ffff0020 !important;
}
</style>
